package xin.yangshuai.juc01.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class ThreadPoolService {

    public static final Logger logger = LoggerFactory.getLogger(ThreadPoolService.class);

    private Object lock = new Object();
    int num = 0;
    Date date = null;

    @Qualifier("taskExecutor1")
    @Autowired
    private Executor taskExecutor1;

    /**
     * 线程池状态
     *
     * @return
     */
    public void threadPoolInfo() {

        ThreadPoolTaskExecutor threadTask = (ThreadPoolTaskExecutor) taskExecutor1;
        ThreadPoolExecutor threadPoolExecutor = threadTask.getThreadPoolExecutor();

        long taskCount = threadPoolExecutor.getTaskCount();
        long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
        int corePoolSize = threadPoolExecutor.getCorePoolSize();
        int maximumPoolSize = threadPoolExecutor.getMaximumPoolSize();
        int activeCount = threadPoolExecutor.getActiveCount();
        int queueSize = threadPoolExecutor.getQueue().size();
        int remainingCapacity = threadPoolExecutor.getQueue().remainingCapacity();
        logger.info("|---------------------------------------------------");
        logger.info("|-提交任务数：{}", taskCount);
        logger.info("|-完成任务数：{}", completedTaskCount);
        logger.info("|-核心线程数：{}", corePoolSize);
        logger.info("|-最大线程数：{}", maximumPoolSize);
        logger.info("|-正在执行任务的线程数：{}", activeCount);
        logger.info("|-队列中的任务数：{}", queueSize);
        logger.info("|-队列中剩余可用的容量：{}", remainingCapacity);
        logger.info("|----------------------------------------------------");

    }

    @Async("taskExecutor")
    public void threadPoolTest(int index) {

        try {
            TimeUnit.MILLISECONDS.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        String name = Thread.currentThread().getName();
        String s = "";
        if (name.contains("nio-8080")) {
            s = "，-----------------------";

            try {
                TimeUnit.MILLISECONDS.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        int i;
        synchronized (lock) {
            Date currentDate = new Date();
            if (date != null) {
                // 大于1秒
                if (currentDate.getTime() - date.getTime() > 1000) {
                    logger.info("---------------------------------------------------------");
                }
            }
            date = currentDate;

            i = num++;
            logger.info("执行异步方法开始，index：{}，执行顺序：{}{}", index, i, s);
        }

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (name.contains("nio-8080")) {
            logger.info("执行异步方法结束，index：{}，执行顺序：{}{}", index, i, s);
        }

    }

    @Async("taskExecutor1")
    public void threadPoolTest1(int index) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String format = simpleDateFormat.format(new Date());
        logger.info("开始异步执行----------------------" + index + "-" + format);

        try {
            TimeUnit.MILLISECONDS.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        String format1 = simpleDateFormat.format(new Date());
//        logger.info("异步执行结束----------------------" + index + "-" + format1);
    }
}
